package com.mind.db.async;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bugull.mongo.MongoBaseEntity;
import com.mind.db.DaoManager;
import com.mind.db.IDao;
import com.mind.db.IEntity;
import com.mind.db.async.model.AsyncBean;
import com.mind.db.async.model.DBUpdateQueue;


/**
 * 更新线程
 * 
 * @author yangshaobo 2012-5-17
 */
public class DbUpdateThread implements Runnable {
	private static Logger log = Logger.getLogger(DbUpdateThread.class);
	private long count = 0; // 计数器
	private long insertCount;
	private long updateCount;
	private long errorCount;
	private String name;
	private DBUpdateQueue queue;
	public DbUpdateThread(DBUpdateQueue queue,String name) {
		this.queue=queue;
		this.name = name;
	}

	@Override
	public void run() {
		while (true) {
			try {
				long queueSize = queue.size();
				if (queueSize == 0) { // 如果无入队元素
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else { // 出队执行更新
					AsyncBean asyncBean = queue.pop();
					if(asyncBean==null){
						log.debug("出队对象=" + asyncBean.getEntity().getClass().getName()
								+ "#" + asyncBean.getEntity().getId()+"----有重复的。");
						continue;
					}
					log.debug("出队对象=" + asyncBean.getEntity().getClass().getSimpleName()
							+ "#" + asyncBean.getEntity().getId());
					IDao<IEntity> dao = DaoManager.getInstance().getDao(
							asyncBean.getEntity().getClass());
					IEntity entity = asyncBean.getEntity();
					switch (asyncBean.getOperationType()) {
					case CREATE:
						dao.insert(entity);
						insertCount++;
						break;
					case UPDATE:
						dao.update(entity);
						updateCount++;
						break;
					}
					count++;
					if (count % 10 == 0) {
						log.info("UQT:" + this.name 
								+ ",新增:" + insertCount
								+ ",更新:" + updateCount
								+ ",出错:" + errorCount
								+ ",总记录:"+ count
								+ ",等待处理数据:"+queue.size());
					}
				}
			} catch (Exception ex) { // 异常
				log.info("*****************************************************************");
				log.error("异步更新出错", ex);
				log.info("*****************************************************************");
				errorCount++;
			}
		}
	}

	public long getCount() {
		return count;
	}

	public long getInsertCount() {
		return insertCount;
	}

	public long getUpdateCount() {
		return updateCount;
	}

	public long getErrorCount() {
		return errorCount;
	}

}